package com.gitee.cui.netty.protocol;

import com.gitee.cui.netty.NettyDemoConfig;
import com.gitee.cui.util.Logger;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.util.concurrent.EventExecutorGroup;

/**
 * ProtoBuf编解码传输服务端代码
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/10/26 9:16
 **/
public class ProtoBufServer {

    private int serverPort;

    private ServerBootstrap bootstrap = new ServerBootstrap();

    public ProtoBufServer(int serverPort) {
        this.serverPort = serverPort;
    }

    public static void main(String[] args) {
        new ProtoBufServer(NettyDemoConfig.SOCKET_SERVER_PORT).runServer();
    }

    /**
     * 运行客户端程序
     */
    private void runServer() {
        NioEventLoopGroup boss = new NioEventLoopGroup(1);
        NioEventLoopGroup worker = new NioEventLoopGroup();
        try {
            bootstrap.group(boss, worker);
            bootstrap.channel(NioServerSocketChannel.class);
            bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
            bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
            bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new ProtobufVarint32FrameDecoder());
                    ch.pipeline().addLast(new ProtobufDecoder(MsgProtos.Msg.getDefaultInstance()));
                    ch.pipeline().addLast(new ProtobufBusinessDecoder());
                }
            });
            bootstrap.localAddress(serverPort);

            ChannelFuture future = bootstrap.bind();
            future.sync();

            ChannelFuture closeFuture = future.channel().closeFuture();
            closeFuture.sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }

    private class ProtobufBusinessDecoder extends ChannelInboundHandlerAdapter {
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            MsgProtos.Msg protoMsg = (MsgProtos.Msg) msg;
            Logger.info("收到一个ProtoBuf POJO => ");
            Logger.info("protoMsg.getId()= " + protoMsg.getId());
            Logger.info("protoMsg.getContent()= " + protoMsg.getContent());
        }
    }
}
